package wsi.dataguide;

import org.rygh.core.html.table.TableData;
import org.rygh.core.html.table.TableTuple;

import wsi.dataguide.tree.WSXmlLeaf;
import wsi.dataguide.tree.WSXmlObject;
import wsi.dataguide.tree.WSXmlTree;

public class XmlTableNode {

	private final WSXmlTree tree;
	private final TableData data;

	public XmlTableNode(String value, TableData data) {
		WSXmlObject obj = new WSXmlObject("node");
		obj.setValue(value);

		tree = new WSXmlTree(obj);
		this.data = data;
	}

	public void convert() {
		TableTuple columns = data.get(0);

		int width = columns.size();

		WSXmlLeaf[] pointers = new WSXmlLeaf[width];
		TableTuple tuple;
		WSXmlLeaf parent;

		for (int i = 1; i < data.size(); i++) {
			tuple = data.get(i);

			for (int j = 0; j < width; j++) {

				if (pointers[j] != null)
					assert pointers[j].getValue().getValue() != null;

				if (pointers[j] == null
						|| tuple.get(j).trim().isEmpty()
						|| !pointers[j].getValue().getValue()
								.equals(tuple.get(j))) {
					pointers[j] = null;

					String str = tuple.get(j).trim();

					if (!str.isEmpty() && !str.equals("&nbsp;")) {
						WSXmlObject obj = new WSXmlObject(columns.get(j));
						obj.setValue(tuple.get(j));

						assert obj.getValue() != null;

						parent = (j == 0) ? (WSXmlLeaf) tree.getRoot()
								: pointers[j - 1];

						pointers[j] = new WSXmlLeaf(parent, obj);
					}

					for (int k = j + 1; k < width; k++)
						pointers[k] = null;
				}
			}
		}
	}

	public String toXmlString() {
		return tree.toWSXmlString();
	}
}
